package offer.nowcoder.array;

/**
 * @author DengYuan2
 * @create 2021-02-09 21:55
 */
public class n_5 {
    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer("We Are Happy.");
        String res = replaceSpace(buffer);
        System.out.println(res);
    }

    /**
     * 我不应该用replace的，看了官方过程
     * 思路：从前往后记录空格个数，从后往前替换
     * @param str
     * @return
     */
    public static String replaceSpace(StringBuffer str) {
        int count=0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i)==' '){
                count++;
            }
        }
        int newLength=str.length()+count*2;
        int j = newLength-1;
        int i = str.length()-1;
        str.setLength(newLength);
        for (;i>=0;i-- ) {
            if (str.charAt(i)==' '){
                str.setCharAt(j--,'0');
                str.setCharAt(j--,'2');
                str.setCharAt(j--,'%');
            }else {
                str.setCharAt(j--,str.charAt(i));
            }

        }
        return str.toString();
    }
}
